
package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.update.UpdateService;
import com.afd.ozblip.update.Version;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.StringUtil;
import com.afd.ozblip.util.ToastUtils;
import com.alibaba.fastjson.JSON;
import com.google.zxing.client.android.CaptureCodeActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class MoreFragment extends Fragment {

    /****************** 常 量 **************************/
    private static final int REQUEST_CODE_BUSINESS_CODE = 100;
    /****************** 视图变量 **************************/
    private LinearLayout settingLayout;
    private LinearLayout saomaoLayout;
    private LinearLayout historyLayout;
    private LinearLayout addBusinessLayout;
    private LinearLayout ideaLayout;
    private LinearLayout updateLayout;
    private LinearLayout tellFriendLayout;
    /****************** 数据变量 **************************/
    private IndexActivity mActivity;
    private Version version;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mActivity = (IndexActivity) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity 必须是 "
                    + IndexActivity.class.getName());
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取参数
        getBundle();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View rootView = inflater.inflate(
                R.layout.more, container, false);
        // 寻找视图
        findViews(rootView);
        // 设置监听
        setListeners();
        return rootView;
    }

    /**
     * 寻找视图
     */
    public void findViews(View rootView) {
        this.settingLayout = (LinearLayout) rootView.findViewById(R.id.ll_more_layout_setting);
        this.saomaoLayout = (LinearLayout) rootView.findViewById(R.id.ll_more_layout_saomiao);
        this.historyLayout = (LinearLayout) rootView.findViewById(R.id.ll_more_layout_history);
        this.addBusinessLayout = (LinearLayout) rootView
                .findViewById(R.id.ll_more_layout_addBusiness);
        this.ideaLayout = (LinearLayout) rootView.findViewById(R.id.ll_more_layout_idea);
        this.updateLayout = (LinearLayout) rootView.findViewById(R.id.ll_more_layout_update);
        this.tellFriendLayout = (LinearLayout) rootView
                .findViewById(R.id.ll_more_layout_tellFriend);
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener moreClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_more_layout_setting:
                        Intent settingIntent = new Intent(mActivity,
                                SettingActivity.class);
                        startActivity(settingIntent);
                        break;
                    case R.id.ll_more_layout_saomiao:
                        final Intent intentInvitationQR = new Intent(
                                mActivity, CaptureCodeActivity.class);
                        startActivityForResult(intentInvitationQR,
                                REQUEST_CODE_BUSINESS_CODE);
                        break;
                    case R.id.ll_more_layout_history:
                        Intent historyIntent = new Intent(mActivity,
                                HistoryActivity.class);
                        startActivity(historyIntent);
                        break;
                    case R.id.ll_more_layout_addBusiness:
                        Intent addBusinessIntent = new Intent(mActivity,
                                AddBusinessActivity.class);
                        startActivity(addBusinessIntent);
                        break;
                    case R.id.ll_more_layout_idea:
                        Intent ideaIntent = new Intent(mActivity,
                                FeedBackActivity.class);
                        startActivity(ideaIntent);
                        break;
                    case R.id.ll_more_layout_update:
                        requestUpdateData();
                        break;

                    default:
                        break;
                }
            }
        };
        this.settingLayout.setOnClickListener(moreClick);
        this.saomaoLayout.setOnClickListener(moreClick);
        this.historyLayout.setOnClickListener(moreClick);
        this.addBusinessLayout.setOnClickListener(moreClick);
        this.ideaLayout.setOnClickListener(moreClick);
        this.updateLayout.setOnClickListener(moreClick);
        this.tellFriendLayout.setOnClickListener(moreClick);
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        // Intent intent = getIntent();
    }

    /**
     * 获取版本更新数据
     */
    private void requestUpdateData() {
        AsyncLoadData ald = new AsyncLoadData(mActivity, "获取版本信息中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> addDishParamMap = new HashMap<String, Object>();
                        // 发送请求
                        byte[] bRecommend = HttpUtil.requestByPost(
                                mActivity, Constants.UPDATE_API,
                                addDishParamMap);
                        if (bRecommend != null) {
                            String jsonStr = new String(bRecommend, "UTF-8");
                            version = JSON.parseObject(jsonStr, Version.class);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        if (version != null) {
                            if (!StringUtil.isNullOrEmpty(version
                                    .getAppVersion())) {
                                if (!getVersion()
                                        .equals(version.getAppVersion())) {
                                    tipDownloadLastAPK();
                                } else {
                                    ToastUtils.showShortToast(mActivity, "当前版本已是最新版", true);
                                }
                            } else {
                                ToastUtils.showShortToast(mActivity, "当前版本已是最新版", true);
                            }

                        } else {
                            ToastUtils.showShortToast(mActivity, "暂无更新", true);
                        }
                    }

                });
        ald.execute(0);

    }

    /**
     * 获取版本号
     * 
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = mActivity.getPackageManager();
            PackageInfo info = manager.getPackageInfo(mActivity.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0";
        }
    }

    /**
     * 提示下载最新版
     */
    public void tipDownloadLastAPK() {

        // 发现新版本，提示用户更新
        AlertDialog.Builder alert = new AlertDialog.Builder(mActivity);
        alert.setTitle(version.getName())
                .setMessage(version.getContent())
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // 开启更新服务UpdateService
                        // 这里为了把update更好模块化，可以传一些updateService依赖的值
                        // 如布局ID，资源ID，动态获取的标题
                        Intent updateIntent = new Intent(mActivity,
                                UpdateService.class);
                        updateIntent.putExtra("title", "OzBlip");
                        updateIntent.putExtra("downloadUrl",
                                version.getAppUrl());
                        mActivity.startService(updateIntent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alert.create().show();
    }

}
